<!-- 饼图 -->
<template>
  <div id="piechart">
    <!-- <div class="title">
      <p>{{ title }}</p>
    </div> -->
    <div ref="piechart" :style="{ height: height, width: width }"></div>
  </div>
</template>

<script>
require('echarts/theme/macarons') // echarts theme
import { formatDuration, parseTime } from "@/utils/index.js";
export default {
  data() {
    return {};
  },
  props: {
    title: {
      type: String,
      default: "综合统计数据分析"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "calc(50vh - 100px)"
    },
    tooltip: {
      type: String,
      default: "数量"
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
        // if(val.length === 0){
        //   const dom = document.getElementById('piechart');
        //   dom.innerHTML = '<div class="el-table__empty-block"><span class="el-table__empty-text">暂无数据</span></div>';
        //   dom.removeAttribute('_echarts_instance_');
        // }else{
        //   this.setOptions(val)
        // }
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() { },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.setOptions(this.chartData)
    // 监听窗口尺寸变化，自适应图表
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 销毁前移除监听器
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      if (this.myChart) {
        this.myChart.resize();
      }
    },
    setOptions(chartData) {
      let that = this
      var showData = []
      var sum = 0, max = 0;
      chartData.forEach(item => {
        sum += item.value
        if (item.value >= max) max = item.value
      })
      // 放大规则
      var number = Math.round(max * 0.1)
      showData = chartData.map(item => {
        return {
          value: number + item.value,
          name: item.name,
          id: item.id,
          num: item.value
        }
      })
      this.myChart = this.$echarts.init(this.$refs.piechart);
      this.myChart.setOption({
        title: {
          left: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: function (param) {
            return `${param.marker}${param.name}<b style="margin-left:20px">${param.data.num}</b>`
          }
        },
        legend: {
          // type: 'scroll',
          show: true,
          // orient: 'vertical',
          // right: 10,
          // top: 20,
          bottom: 5,
          // width: 70,
          formatter: function (name) {
            //通过name获取到数组对象中的单个对象
            let singleData = chartData.filter(function (item) {
              return item.name == name
            })
            return `${name} ( ${that.title.indexOf('使用时长') !== -1 ? formatDuration(singleData[0].value) : singleData[0].value} )`;
          }
        },
        series: [
          {
            type: "pie",
            // roseType: 'area',
            radius: ['50%', '60%'],
            center: ['50%', '50%'],
            data: showData,
            label: {
              normal: {
                show: false,
                formatter: function (param) {
                  return param.name + ' (' + (`${that.title.indexOf('使用时长') !== -1 ? formatDuration(param.value - number) : param.value - number}`) + ')'
                }
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0
              }
            },
            itemStyle: {
              color: function (params) {
                var colorList = [
                  '#0075FF', '#16CE8A', '#FFBB00', '#FD8854', '#8544d6', '#ec61a4', '#ec6561', '#d0ec61', '#58aaff', '#08fafb'
                ];
                // 使用取余运算使颜色循环使用
                return colorList[params.dataIndex % colorList.length];
              }
            }
          }
        ]
      });
      this.myChart.off('click');
      this.myChart.on('click', (params) => {
        this.$emit('pieclick', params.name, this.title, params.data.id)
      });
    }
  }
};
</script>
<style scoped></style>